package com.atguigu.day01;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName SyncLockDemo
 * @Description 此类描述:synchronized vs lock
 * @Author dangchen
 * @DateTime 2022-09-06 19:42
 * @Version 1.0
 */
public class SyncLockDemo {
   public synchronized void m1(){
       System.out.println(Thread.currentThread().getName() + "\t ----- come in");
       try {
           TimeUnit.SECONDS.sleep(3);
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
       System.out.println(Thread.currentThread().getName() + "\t ----- leave out");
   }

   Lock lock = new ReentrantLock();
   public void m2(){
       if (lock.tryLock()){
           try {
               System.out.println(Thread.currentThread().getName() + "\t ----- come in");
               try {
                   TimeUnit.SECONDS.sleep(3);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               System.out.println(Thread.currentThread().getName() + "\t ----- leave out");
           }finally {
               lock.unlock();
           }
       }else{
           System.out.println(Thread.currentThread().getName() + "\t ----- 抢锁失败,立刻离开");
       }
   }

   public void m3(){
       try {
           if (lock.tryLock(3L,TimeUnit.SECONDS)){
               try {
                   System.out.println(Thread.currentThread().getName() + "\t ----- come in");
                   try {
                       TimeUnit.SECONDS.sleep(1);
                   } catch (InterruptedException e) {
                       e.printStackTrace();
                   }
                   System.out.println(Thread.currentThread().getName() + "\t ----- leave out");
               }finally {
                   lock.unlock();
               }
           }else {
               System.out.println(Thread.currentThread().getName() + "\t ----- 抢锁失败,过时不候");
           }
       } catch (InterruptedException e) {
           e.printStackTrace();
       }
   }

    public static void main(String[] args) {
        SyncLockDemo syncLockDemo = new SyncLockDemo();

        new Thread(new Runnable() {
            @Override
            public void run() {
                syncLockDemo.m3();
            }
        },"t1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                syncLockDemo.m3();
            }
        },"t2").start();

        System.out.println("Aa".hashCode());
        System.out.println("BB".hashCode());

    }
}
